package xxl.robotlegs.extensions.viewprocessormap 
{
	import xxl.robotlegs.extensions.viewmanager.api.IViewHandler;
	import xxl.robotlegs.extensions.viewmanager.api.IViewManager;
	import xxl.robotlegs.extensions.viewprocessormap.api.IViewProcessorFactory;
	import xxl.robotlegs.extensions.viewprocessormap.api.IViewProcessorMap;
	import xxl.robotlegs.extensions.viewprocessormap.impl.ViewProcessorFactory;
	import xxl.robotlegs.extensions.viewprocessormap.impl.ViewProcessorMap;
	import xxl.robotlegs.framework.api.IContext;
	import xxl.robotlegs.framework.api.IExtension;
	import xxl.robotlegs.framework.api.IInjector;
	/**
	 * ...
	 * @author XXL
	 */
	public class ViewProcessorMapExtension implements IExtension
	{
		private var _injector:IInjector;
		private var _viewProcessorMap:IViewProcessorMap;
		private var _viewManager:IViewManager;
		private var _viewProcessorFactory:IViewProcessorFactory;
		
		public function ViewProcessorMapExtension() 
		{
			
		}
		
		public function toString():String
		{
			return "ViewProcessorMapExtension（简介：提供一个IViewProcessorMap，可对添加到场景上的显示元件做一些额外处理操作";
		}
		
		private function beforeInitializing():void
		{
			_viewProcessorMap = _injector.getInstance(IViewProcessorMap);
			_viewProcessorFactory = _injector.getInstance(IViewProcessorFactory);
			if (_injector.satisfiesDirectly(IViewManager))
			{
				_viewManager = _injector.getInstance(IViewManager);
				_viewManager.addViewHandler(_viewProcessorMap as IViewHandler);
			}
		}
		
		private function beforeDestroying():void
		{
			_viewProcessorFactory.runAllUnprocessors();
			if (_injector.satisfiesDirectly(IViewManager))
			{
				_viewManager = _injector.getInstance(IViewManager);
				_viewManager.removeViewHandler(_viewProcessorMap as IViewHandler);
			}
		}
		
		private function whenDestroying():void
		{
			if (_injector.satisfiesDirectly(IViewProcessorMap))
			{
				_injector.unmap(IViewProcessorMap);
			}
			if (_injector.satisfiesDirectly(IViewProcessorFactory))
			{
				_injector.unmap(IViewProcessorFactory);
			}
		}
		
		/* INTERFACE xxl.robotlegs.framework.api.IExtension */
		
		public function extend(context:IContext):void 
		{
			context.beforeInitializing(beforeInitializing);
			context.beforeDestroying(beforeDestroying);
			context.whenDestroying(whenDestroying);
			_injector = context.injector;
			_injector.map(IViewProcessorFactory).toValue(new ViewProcessorFactory(_injector.createChild()));
			_injector.map(IViewProcessorMap).toSingleton(ViewProcessorMap);
		}
		
	}

}